import { PayloadAction, createSlice } from '@reduxjs/toolkit';
import { User } from '../interface/user'
import { fetchUserData } from '../utils/user';

const fetchUserInfo = (): User => {
    try {
        return fetchUserData() || defaultValue
    } catch (error) {
        return defaultValue
    }
}

const defaultValue: User = {
    username: '',
    icon: '',
    email: '',
    code: '',
    userIdentity: 0,
    token: '',
    customerId: '',
    inviter: '',
    inviteUrl: '',
}

type PartialUser<T extends keyof User> = {
    [K in T]?: K extends keyof User ? User[K] : never;
};

export const userSlice = createSlice({
    name: 'user',
    initialState: fetchUserInfo(),
    reducers: {
        update: (state, action: { payload: User }) => {
            return {
                ...state,
                ...action.payload
            }
        },
        updateInfo: (state, action: PayloadAction<PartialUser<keyof User>>) => {
            Object.assign(state, action.payload);
        },

        clear: (state) => {
            return {
                ...state,
                ...defaultValue
            }
        }
    },
});

export const { update, clear, updateInfo } = userSlice.actions;

export default userSlice.reducer;